#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);

    connect(&subscriber,&SimpleSubscriber::received,this,&Dialog::onReceived);
    if(!publisher.wakeup())
        ui->reply->append("publisher failure");
    if(!subscriber.wakeup())
        ui->reply->append("subscriber failure");
}

Dialog::~Dialog()
{
    if(publisher.isConnectedToHost())
        publisher.disconnectFromHost();

    if(subscriber.isConnectedToHost())
        subscriber.disconnectFromHost();

    delete ui;
}

void Dialog::on_btn_publish_clicked()
{
    if(!publisher.isConnectedToHost())
        return;

    QString message=ui->message->toPlainText();
    publisher.pub(message);
}

void Dialog::onReceived(const QMQTT::Message &message)
{
    QString payload=message.payload();
    ui->reply->append(payload);
}
